package com.ruoyi.gd.mail.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gd.ywdwgd.domain.ZYwdwgd;
import com.ruoyi.gd.ywdwgd.domain.bo.ZYwdwgdBo;
import com.ruoyi.gd.ywdwgd.service.IZYwdwgdService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.gd.mail.domain.bo.ZMailBo;
import com.ruoyi.gd.mail.domain.vo.ZMailVo;
import com.ruoyi.gd.mail.domain.ZMail;
import com.ruoyi.gd.mail.mapper.ZMailMapper;
import com.ruoyi.gd.mail.service.IZMailService;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 快递邮寄Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-23
 */
@RequiredArgsConstructor
@Service
public class ZMailServiceImpl implements IZMailService {

    private final ZMailMapper baseMapper;

    @Resource
    private IZYwdwgdService zywdwgdService;

    /**
     * 查询快递邮寄
     */
    @Override
    public ZMailVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询快递邮寄列表
     */
    @Override
    public TableDataInfo<ZMailVo> queryPageList(ZMailBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZMail> lqw = buildQueryWrapper(bo);
        Page<ZMailVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询快递邮寄列表
     */
    @Override
    public List<ZMailVo> queryList(ZMailBo bo) {
        LambdaQueryWrapper<ZMail> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZMail> buildQueryWrapper(ZMailBo bo) {
        LambdaQueryWrapper<ZMail> lqw = Wrappers.lambdaQuery();
        try {
            // 处理空格
            bo.setZbbh(StringUtils.trimField(bo, "zbbh"));
            bo.setKh(StringUtils.trimField(bo, "kh"));
            bo.setDz(StringUtils.trimField(bo, "dz"));
            bo.setKdh(StringUtils.trimField(bo, "kdh"));
            LoginUser loginUser = LoginHelper.getLoginUser();
            lqw.eq(StringUtils.isNotBlank(bo.getZbbh()), ZMail::getZbbh, bo.getZbbh());
            lqw.eq(StringUtils.isNotBlank(bo.getKhid()), ZMail::getKhid, bo.getKhid());
            lqw.like(StringUtils.isNotBlank(bo.getKh()), ZMail::getKh, bo.getKh());
            lqw.eq(StringUtils.isNotBlank(bo.getDz()), ZMail::getDz, bo.getDz());
            lqw.eq(StringUtils.isNotBlank(bo.getYjsp()), ZMail::getYjsp, bo.getYjsp());
            lqw.eq(bo.getNumber() != null, ZMail::getNumber, bo.getNumber());
//            lqw.eq(StringUtils.isNotBlank(bo.getKdgs()), ZMail::getKdgs, bo.getKdgs());
            lqw.eq(StringUtils.isNotBlank(bo.getKdh()), ZMail::getKdh, bo.getKdh());
            lqw.eq(StringUtils.isNotBlank(bo.getBz()), ZMail::getBz, bo.getBz());
            if(!"admin".equals(loginUser.getUsername())) {
                List<String> strings = Arrays.asList("0");
                lqw.in(ZMail::getDelFlag, strings);
            }
            // 添加时间条件
            if (bo.getParams()!=null && bo.getParams().size() > 0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Object start = bo.getParams().get("startTime");
                Object end = bo.getParams().get("endTime");
                if (null != start && null != end) {
                    Date startTime = format.parse((String) start);
                    Date endTime = format.parse((String) end);
                    if (startTime != null && endTime != null) {
                        lqw.ge(ZMail::getYjsj, startTime);
                        lqw.le(ZMail::getYjsj, endTime);
                    }
                }
            }
            // 判断当前的邮寄状态
            if (StringUtils.isNotEmpty(bo.getYjzt())) {
                List<String> strings = Arrays.asList(bo.getYjzt().split(","));
                lqw.in(ZMail::getYjzt, strings);
            }
            // 判断当前快递公司
            if (StringUtils.isNotEmpty(bo.getKdgs())) {
                List<String> strings = Arrays.asList(bo.getKdgs().split(","));
                lqw.in(ZMail::getKdgs, strings);
            }
            // 查询送回取回状态
            if (StringUtils.isNotEmpty(bo.getShqhzt())) {
                List<String> strings = Arrays.asList(bo.getShqhzt().split(","));
                lqw.in(ZMail::getShqhzt, strings);
            }
            // 送回状态
            if (StringUtils.isNotEmpty(bo.getSh())) {
                List<String> strings = Arrays.asList(bo.getSh().split(","));
                if (strings.contains("bksh") && strings.contains("zksh")) {
                    lqw.eq(ZMail::getKdgs, "sh").or().ne(ZMail::getKdgs, "sh");
                }else if (strings.contains("bksh")) {
                    lqw.ne(ZMail::getKdgs, "sh");
                }else if (strings.contains("zksh")) {
                    lqw.eq(ZMail::getKdgs, "sh");
                }
            }
            // 取回状态
            if (StringUtils.isNotEmpty(bo.getQh())) {
                List<String> strings = Arrays.asList(bo.getQh().split(","));
                if (strings.contains("bkqh") && strings.contains("zkqh")) {
                    lqw.eq(ZMail::getKdgs, "qh").or().ne(ZMail::getKdgs, "qh");
                }else if (strings.contains("bkqh")) {
                    lqw.ne(ZMail::getKdgs, "qh");
                }else if (strings.contains("zkqh")) {
                    lqw.eq(ZMail::getKdgs, "qh");
                }
            }
            // 通过时间进行倒叙排序
            lqw.orderByDesc(ZMail::getYjsj);
            lqw.orderByDesc(ZMail::getCreateTime);
        }catch (Exception e){
            e.printStackTrace();
        }

        return lqw;
    }

    /**
     * 新增快递邮寄
     */
    @Override
    public Boolean insertByBo(ZMailBo bo) {
        ZMail add = BeanUtil.toBean(bo, ZMail.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改快递邮寄
     */
    @Override
    public Boolean updateByBo(ZMailBo bo) {
        ZMail update = BeanUtil.toBean(bo, ZMail.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZMail entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除快递邮寄
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.batchDeleteIds(ids) > 0;
    }

    @Override
    public List<ZMailVo> queryListByIds(String ids) {
        String[] split = ids.split(",");
        List<ZMailVo> list = baseMapper.selectByIds(split);
        return list;
    }

    /**
     * 更新完工单状态
     * @param bo
     * @return
     */
    @Override
    public Boolean syncStatusZt(ZMailBo bo) {
        // 添加邮寄物品是证书的数据
        bo.setYjsp("2");
        List<ZMailVo> zMailVos = queryList(bo);
        List<ZYwdwgdBo> zywdwgdList = new ArrayList<>();
        for (ZMailVo zMailVo : zMailVos) {
            ZYwdwgdBo zYwdwgdBo = new ZYwdwgdBo();
            zYwdwgdBo.setWgdh(zMailVo.getWgbb()); // 设置完工编号
            if("1".equals(zMailVo.getYjzt())) {  //邮寄状态为 邮寄
                zYwdwgdBo.setYyjkh(zMailVo.getYjzt());
            }else {
                zYwdwgdBo.setYyjkh("0");
            }
            zywdwgdList.add(zYwdwgdBo);
        }
        // 通过总部编号批量更新邮寄状态
        int row = zywdwgdService.batchUpdateByWgbh(zywdwgdList);
        return row > 0;
    }
}
